package cn.Filter.LoginFileter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
	private String excludedPages;
	private String[] excludedPageArray;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		String userid = null;
		if (session.getAttribute("userId") != null) {
			userid = (String) session.getAttribute("userId");
		}
		String basePath=req.getContextPath();
		String uri = req.getRequestURI();
		boolean isExcludedPage = false;
		for (String page : excludedPageArray) {
			if (uri.indexOf(page)!=-1) {
				isExcludedPage = true;
				break;
			}
		}
		if (!isExcludedPage && userid == null) {// 用户未登录必须登录后才能访问
			resp.sendRedirect(basePath+"/Employee/login.jsp?msg=-2");
		}else{
			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		excludedPages = sc.getInitParameter("excludedPages");
		if (excludedPages != null)
			excludedPageArray = excludedPages.split(",");
		return;
	}

}
